package com.example.uibestpractice;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Msg> mMsgList = new ArrayList<>();
    private Button send;
    private EditText edt;
    private RecyclerView rv;
    private MsgAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化消息数据
        InitMsg();
        rv = (RecyclerView)findViewById(R.id.msg_recycler_view);
        //给RecyclerView设置布局方式
        LinearLayoutManager llm = new LinearLayoutManager(this);
        rv.setLayoutManager(llm); //默认纵向
        //绑定数据
        adapter = new MsgAdapter(mMsgList);
        rv.setAdapter(adapter);
        //完成点击按钮，输入框内容发送成功
        sendMsg();
    }
    private void InitMsg(){
        mMsgList.add(new Msg("你好呀",Msg.TYPE_RECEIVED)); //接收消息
        mMsgList.add(new Msg("hello",Msg.TYPE_SEND)); //发送消息
        mMsgList.add(new Msg("最近怎么样？",Msg.TYPE_RECEIVED)); //接收消息
    }
    private void sendMsg(){
        //获取点击按钮
        send = (Button)findViewById(R.id.send);
        //获取输入框
        edt = (EditText)findViewById(R.id.input_text);
        //给send按钮绑定点击事件
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = edt.getText().toString();
                Msg msg = new Msg(content,Msg.TYPE_SEND);
                mMsgList.add(msg);// 将消息加入集合
                // 适配器去刷新数据


                adapter.notifyItemInserted(mMsgList.size() - 1);
                //将显示的数据定位到最后一行，得到最后发出的一条消息。(避免消息多)
                rv.scrollToPosition(mMsgList.size() - 1);
                //最后清空输入框的内容
                edt.setText("");
            }
        });
    }
}